package com.njitzx.fileupload.service.impl;

import com.njitzx.fileupload.mapper.ArticleMapper;
import com.njitzx.fileupload.pojo.Article;
import com.njitzx.fileupload.pojo.UserDTO;
import com.njitzx.fileupload.service.ArticleService;
import com.njitzx.fileupload.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

import static com.njitzx.fileupload.constant.RedisConstant.articleLike;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void publishArticle(Article article) {
//        UserDTO user = UserHolder.getUser();
//        Integer userId = user.getId();
        article.setAuthorId(1);
        article.setCreatedDate(new Date());
        article.setUpdatedDate(new Date());
        articleMapper.insert(article);
    }

    @Override
    public void likeArticle(Integer id) {
        //应该存储的是这个文章背哪些用户点赞了
        redisTemplate.opsForSet().add(articleLike + id, 2);
        // 用一个定时任务  隔一段时间将redis中的点赞数同步到数据库中
    }

    @Override
    public Integer getArticleLikeCount(Integer id) {
        Set<Object> members = redisTemplate.opsForSet().members(articleLike + id);
        if (members != null) {
            return members.size();
        }
        return 0;
    }
}
